from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from.models import Course, CourseCategory
from django.contrib import messages


# 课程列表视图，可按分类筛选课程
def course_list(request, category_slug=None):
    category = None
    categories = CourseCategory.objects.all()
    courses = Course.objects.all()
    if category_slug:
        category = get_object_or_404(CourseCategory, slug=category_slug)
        courses = courses.filter(category=category)
    return render(request, 'courses/course_list.html', {
        'category': category,
        'categories': categories,
        'courses': courses
    })


# 课程详情视图
def course_detail(request, course_id):
    course = get_object_or_404(Course, id=course_id)
    return render(request, 'courses/course_detail.html', {'course': course})


# 用户收藏课程视图
@login_required
def favorite_course(request, course_id):
    course = get_object_or_404(Course, id=course_id)
    if request.user.favorites.filter(id=course_id).exists():
        messages.warning(request, '你已经收藏过该课程了哦。')
    else:
        request.user.favorites.add(course)
        messages.success(request, '课程已成功收藏！')
    return redirect('course_detail', course_id=course_id)